package com.yimi.yinhepda.views.unload_module.palletbind;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.OffLineUnBindAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.OffLineUnbindTableDao;
import com.yimi.yinhepda.db.table.OffLineUnbindTable;
import com.yimi.yinhepda.entity.bean.StatForkliftTaskDetailIndex;
import com.yimi.yinhepda.entity.request.OffLineUnBindRequest;
import com.yimi.yinhepda.entity.response.AreaCodeAndNextStationResponse;
import com.yimi.yinhepda.entity.response.SuccessResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.NetworkUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.UcWaybillValidate;

import org.jetbrains.annotations.NotNull;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.pda.ym.utils.Constants.getOffLinePalletTaskNo;

/**
 * 离线解绑界面
 *
 * @author xionggaosheng
 */
public class OffLineUnBindActivity extends BaseTitleActivity implements CommonViewHolder.onItemCommonClickListener {

    /**
     * 列表
     */
    private RecyclerView listView;
    /**
     * 适配器
     */
    private OffLineUnBindAdapter adapter;
    /**
     * 返回bar
     */
    private ImageButton ibBack;
    /**
     * 返回按钮
     */
    private Button btnBack;
    /**
     * 提交按钮
     */
    private Button btnCommit;
    /**
     * 数据
     */
    List<StatForkliftTaskDetailIndex> dataList = new ArrayList<>();

    public OffLineUnBindActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "离线解绑";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_offline;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        listView = findViewById(R.id.rv_task_no);
        ibBack = findViewById(R.id.ib_back);
        btnBack = findViewById(R.id.btn_back);
        btnCommit = findViewById(R.id.btn_commit);

        ibBack.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        btnCommit.setOnClickListener(this);

        adapter = new OffLineUnBindAdapter(this, dataList, this);
        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.setAdapter(adapter);
    }

    @Override
    protected void handleBarCode(final String result) {
        if (result == null) {
            showToast("运单扫描失败");
        } else if (!StringUtils.isWaybillNo(result) && !UcWaybillValidate.validate(result)) {
            showToast("单号不规范！(" + result + ")");
        } else {
            for (StatForkliftTaskDetailIndex statForkliftTaskDetailIndex : dataList) {
                if (statForkliftTaskDetailIndex.getChildWaybillNo().equals(result)) {
                    showToast("重复子运单(" + result + ")");
                    return;
                }
            }

            if (!NetworkUtil.isConnect(this)) {
                //离线时 不查仓库和下一站
                StatForkliftTaskDetailIndex statForkliftTaskDetailIndex = new StatForkliftTaskDetailIndex();
                statForkliftTaskDetailIndex.setChildWaybillNo(result);
                statForkliftTaskDetailIndex.setWaybillNo(BindUtil.getWaybillNoByScanResult(result));
                dataList.add(statForkliftTaskDetailIndex);
                adapter.notifyDataSetChanged();
            } else {
                //在线时 查仓库和下一站
                showPgDlg("数据请求中...");
                Map map = new HashMap<String, String>(1);
                map.put("waybillNo", BindUtil.getWaybillNoByScanResult(result));

                new NetRequest().setMethod(NetRequest.Method.GET)
                        .setUrl(BindUtil.getQueryAreaCodeUrl(result))
                        .setParams(map)
                        .setResponsClazz(AreaCodeAndNextStationResponse.class)
                        .setConnTimeOut(10 * 1000)
                        .execute(new UICallBack() {
                            @Override
                            public void onError(String msg) {
                                dismissPgDlg();
                                if (msg != null) {
                                    showToast(msg);
                                } else {
                                    showToast("服务器出错了!");
                                }
                                SoundVibratorManager.playSound(2);
                                dismissPgDlg();
                            }

                            @Override
                            public void onSuccess(Object obj) {
                                dismissPgDlg();
                                AreaCodeAndNextStationResponse response = (AreaCodeAndNextStationResponse) obj;
                                if (response.isSuccess()) {
                                    if (response.getData() != null) {
                                        StatForkliftTaskDetailIndex bean = new StatForkliftTaskDetailIndex();
                                        bean.setChildWaybillNo(result);
                                        bean.setWaybillNo(BindUtil.getWaybillNoByScanResult(result));
                                        bean.setAreaCode(response.getData().getStorageCode() == null ? "" : response.getData().getStorageCode());
                                        bean.setNextDept(response.getData().getNextDeptName() == null ? "" : response.getData().getNextDeptName());
                                        bean.setNextDeptCode(response.getData().getNextDeptCode() == null ? "" : response.getData().getNextDeptCode());
                                        dataList.add(bean);
                                        adapter.notifyDataSetChanged();
                                        SoundVibratorManager.playSound(1);
                                    } else {
                                        showToast("无运单信息！");
                                        SoundVibratorManager.playSound(2);
                                    }
                                }
                            }
                        });
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_commit:
                //提交
                updateOffLineData();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClickListener(int position) {
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    /**
     * 提交离线解绑界面
     */
    private void updateOffLineData() {
        if (dataList == null || dataList.isEmpty()) {
            showToast("无数据提交!");
            SoundVibratorManager.playSound(2);
            return;
        }
        OffLineUnBindRequest offLineUnBindRequest = new OffLineUnBindRequest();
        String palletTaskNo = getOffLinePalletTaskNo();
        List<OffLineUnbindTable> list = new ArrayList();
        for (StatForkliftTaskDetailIndex statForkliftTaskDetailIndex : dataList) {
            OffLineUnbindTable offLineUnbindBean = new OffLineUnbindTable();
            offLineUnbindBean.setChildWaybillNo(statForkliftTaskDetailIndex.getChildWaybillNo());
            offLineUnbindBean.setWaybillNo(statForkliftTaskDetailIndex.getWaybillNo());
            offLineUnbindBean.setForkliftNo(palletTaskNo);
            offLineUnbindBean.setOperDeptCode(sharedPreferUtil.getDeptCode());
            offLineUnbindBean.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
            offLineUnbindBean.setOperTime(DateHelper.getDateTimeFormateForSimple(new Date()));
            offLineUnbindBean.setCreateTime(Constants.GetSysTime());
            offLineUnbindBean.setType(offLineUnbindBean.getWaybillNoType());
            list.add(offLineUnbindBean);
        }
        offLineUnBindRequest.setStatOfflineVos(list);

        if (!NetworkUtil.isConnect(this)) {
            //如果没网保存本地数据库
            OffLineUnbindTableDao dao = new OffLineUnbindTableDao();
            try {
                dao.insert(list);
                showToast("数据存入本地数据库成功");
                finish();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {

            showToast("数据提交中...");
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setUrl(Constants.URL_OFFLINE_UNBIND_FORKLIFT)
                    .setRequestObject(offLineUnBindRequest)
                    .setResponsClazz(SuccessResponse.class)
                    .setConnTimeOut(10 * 1000)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            if (msg != null) {
                                showToast(msg);
                            } else {
                                showToast("服务器出错了!");
                            }
                            SoundVibratorManager.playSound(2);
                            dismissPgDlg();
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            SuccessResponse response = (SuccessResponse) obj;
                            if (response.isSuccess()) {
                                showToast("离线解绑提交成功");
                                finish();
                            }

                            SoundVibratorManager.playSound(1);
                            dismissPgDlg();
                        }
                    });
        }
    }

    /**
     * 下载解绑数据
     */
    private void updateScanData() {

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_FORK_UPDATE_SCAN_STATE)
                .setRequestObject(new OffLineUnBindRequest())
                .setResponsClazz(SuccessResponse.class)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        SuccessResponse response = (SuccessResponse) obj;
                        if (response.isSuccess()) {

                        }
                    }
                });
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
